package com.bzkj.basicinfo.service.basic.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.bzkj.basicinfo.domain.basic.BasicStoUnit;
import com.bzkj.basicinfo.domain.wms.WmsStoStockEntity;
import com.bzkj.basicinfo.mapper.BasicStoUnitMapper;
import com.bzkj.basicinfo.mapper.WmsStoStockMapper;
import com.bzkj.basicinfo.service.basic.BasicStoUnitService;
import com.bzkj.basicinfo.utils.GenerateQRCodeUtils;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.enums.DataSourceType;
import com.bzkj.common.utils.StringUtils;
import com.bzkj.framework.datasource.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author wl
 * @description 针对表【basic_sto_unit(WMS货位信息表)】的数据库操作Service实现
 * @createDate 2024-12-13 12:08:36
 */
@Slf4j
@Service
public class BasicStoUnitServiceImpl implements BasicStoUnitService {

    @Autowired
    private BasicStoUnitMapper basicStoUnitMapper;

    @Autowired
    private WmsStoStockMapper wmsStoStockMapper;

    @Autowired
    private GenerateQRCodeUtils gqrc;

    @Override
    public List<BasicStoUnit> findBasicStoUnit(BasicStoUnit entity) {
        if (Objects.nonNull(entity.getDosageId())) {
            entity.setStoAreaIds(Arrays.asList(entity.getDosageId().split(",")));
        }
        return basicStoUnitMapper.findBasicStoUnit(entity);
    }

    @Override
    public AjaxResult updateBasicStoUnitEnableStatusAll(List<Integer> list, String status) {
        if (list.isEmpty())
            return AjaxResult.error("修改失败,请选择数据");
        try {
            //校验货位是否被使用
            if (status.equals("0")) {
                StringBuilder sb = new StringBuilder();
                list.forEach(stoUnitId -> {
                    log.info("当前数据源：{}", DynamicDataSourceContextHolder.getDataSourceType());
                    BasicStoUnit byStoUnitId = basicStoUnitMapper.getByStoUnitId(String.valueOf(stoUnitId));
                    try{
                        List<WmsStoStockEntity> stock = wmsStoStockMapper.findWmsStoStockByStoUnitId(byStoUnitId.getStoUnitCode());
                        if (CollectionUtil.isNotEmpty(stock)) {
                            sb.append(byStoUnitId.getStoUnitCode());
                            sb.append(" ");
                        }
                    }catch (Exception e){
                        try{
                            DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
                            log.info("手动切换到从库，当前数据源：{}", DynamicDataSourceContextHolder.getDataSourceType());
                            List<WmsStoStockEntity> stock = wmsStoStockMapper.findWmsStoStockByStoUnitId(byStoUnitId.getStoUnitCode());
                            if (CollectionUtil.isNotEmpty(stock)) {
                                sb.append(byStoUnitId.getStoUnitCode());
                                sb.append(" ");
                            }
                        }finally {
                            DynamicDataSourceContextHolder.clearDataSourceType();
                        }
                    }
                });
                if (StringUtils.isNotBlank(sb)) {
                    return AjaxResult.error(sb + "以上货位已使用，修改失败");
                }
            }
            basicStoUnitMapper.updateBasicStoUnitEnableStatusAll(list, status);
            return AjaxResult.success("修改成功");
        } catch(Exception e) {
            log.error("修改失败:{}", e);
            return AjaxResult.error("修改失败");
        }
    }

    @Override
    public AjaxResult updateBasicStoUnitEnableStatus(String enableState, String stoUnitId) {
        try {
            //校验货位是否被使用
            if (enableState.equals("0")) {
                BasicStoUnit byStoUnitId = basicStoUnitMapper.getByStoUnitId(stoUnitId);
                //根据货位编码去库存中查询货位是否被使用
                try{
                    List<WmsStoStockEntity> stock = wmsStoStockMapper.findWmsStoStockByStoUnitId(byStoUnitId.getStoUnitCode());
                    if (CollectionUtil.isNotEmpty(stock)) {
                        return AjaxResult.error("货位已使用，修改失败");
                    }
                }catch (Exception e){
                    try{
                        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
                        log.info("手动切换到从库，当前数据源：{}", DynamicDataSourceContextHolder.getDataSourceType());
                        List<WmsStoStockEntity> stock = wmsStoStockMapper.findWmsStoStockByStoUnitId(byStoUnitId.getStoUnitCode());
                        if (CollectionUtil.isNotEmpty(stock)) {
                            return AjaxResult.error("货位已使用，修改失败");
                        }
                    }finally {
                        DynamicDataSourceContextHolder.clearDataSourceType();
                    }
                }

            }
            basicStoUnitMapper.updateBasicStoUnitEnableStatus(enableState, stoUnitId);
            return AjaxResult.success("修改成功");
        } catch (Exception e) {
            log.error("修改失败:{}", e);
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 根据条件查询出货位信息并生成二维码
     *
     * @param stoUnitIds
     * @return
     */
    @Override
    public AjaxResult printStoUnit(List<Integer> stoUnitIds) {
        if (CollectionUtil.isEmpty(stoUnitIds)) {
            return AjaxResult.warn("请先选择所要打印的数据");
        }
        List<BasicStoUnit> basicStoUnit = basicStoUnitMapper.printBasicStoUnit(stoUnitIds);
        gqrc.crateQRCode(basicStoUnit);

        return AjaxResult.success(basicStoUnit);
    }

    @Override
    public AjaxResult deleteByStoUnitId(String stoUnitId) {
        StringBuilder sb = new StringBuilder();
        //根据货位id查询货位数据
        BasicStoUnit byStoUnitId = basicStoUnitMapper.getByStoUnitId(String.valueOf(stoUnitId));
        //根据货位编码去库存中查询货位是否被使用
        List<WmsStoStockEntity> stock = wmsStoStockMapper.findWmsStoStockByStoUnitId(byStoUnitId.getStoUnitCode());
        if (CollectionUtil.isNotEmpty(stock)) {
            sb.append(byStoUnitId.getStoUnitCode());
        }
        if (StringUtils.isNotBlank(sb)) {
            return AjaxResult.error("货位已使用，删除失败");
        } else {
            int i = basicStoUnitMapper.deleteByStoUnitId(stoUnitId);
            if (i > 0) {
                return AjaxResult.success("删除成功");
            } else {
                return AjaxResult.success("删除失败");
            }
        }
    }

    @Override
    public AjaxResult batchDeleteByStoUnitId(List<String> stoUnitIds) {
        //校验货位是否被使用
        StringBuilder sb = new StringBuilder();
        stoUnitIds.forEach(stoUnitId -> {
            log.info("当前数据源：{}", DynamicDataSourceContextHolder.getDataSourceType());
            BasicStoUnit byStoUnitId = basicStoUnitMapper.getByStoUnitId(String.valueOf(stoUnitId));
            try{
                List<WmsStoStockEntity> stock = wmsStoStockMapper.findWmsStoStockByStoUnitId(byStoUnitId.getStoUnitCode());
                if (CollectionUtil.isNotEmpty(stock)) {
                    sb.append(byStoUnitId.getStoUnitCode());
                    sb.append(" ");
                }
            }catch (Exception e){
                try{
                    DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
                    log.info("手动切换到从库，当前数据源：{}", DynamicDataSourceContextHolder.getDataSourceType());
                    List<WmsStoStockEntity> stock = wmsStoStockMapper.findWmsStoStockByStoUnitId(byStoUnitId.getStoUnitCode());
                    if (CollectionUtil.isNotEmpty(stock)) {
                        sb.append(byStoUnitId.getStoUnitCode());
                        sb.append(" ");
                    }
                }finally {
                    DynamicDataSourceContextHolder.clearDataSourceType();
                }
            }
        });
        if (StringUtils.isNotBlank(sb)) {
            return AjaxResult.error(sb + "以上货位已使用，删除失败");
        }else{
            int i =basicStoUnitMapper.batchDeleteByStoUnitId(stoUnitIds);
             if(i>0){
                return AjaxResult.success("删除成功");
            }else{
                return AjaxResult.success("删除失败");
            }
        }
    }
}




